package org.jakim.servlets;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.jakim.entity.User;

/**
 * Servlet implementation class RegistrationServlet
 */
@WebServlet("/RegistrationServlet")
public class RegistrationServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RegistrationServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String userName = request.getParameter("userName");
		String userSirName = request.getParameter("userSirName");
		String userEmail = request.getParameter("userEmail");
		String userPassword = request.getParameter("userPassword");
		String userCity = request.getParameter("userCity");
		String userCountry = request.getParameter("userCountry");
		int userBirthDay = Integer.parseInt(request.getParameter("userBirthDay"));
		int userBirthMonth = Integer.parseInt(request.getParameter("userBirthMonth"));
		int userBirthYear = Integer.parseInt(request.getParameter("userBirthYear"));
		
		Calendar calDOB = GregorianCalendar.getInstance(Locale.getDefault());
		Calendar calNow = GregorianCalendar.getInstance(Locale.getDefault());
		calDOB.set(userBirthYear, userBirthMonth, userBirthDay);
		calNow.setTime(new Date());
		
		int userAger = calNow.get(Calendar.YEAR) - calDOB.get(Calendar.YEAR);
		
		
		/* TODO: make a user parameters validation!
		 * Check for value duplications
		 * Check for strings length
		 * Age checks
		 * May be it is nice all these to be check in registration.jsp
		*/
		
		User newUser = new User();
		newUser.setUserAge(userAger);
		newUser.setUserCity(userCity);
		newUser.setUserCountry(userCountry);
		newUser.setUserName(userName);
		newUser.setUserEmail(userEmail);
		newUser.setUserPassword(userPassword);
		newUser.setUserSirName(userSirName);
		
		HttpSession httpSeesion = request.getSession();

		httpSeesion.setAttribute("User", newUser);
		/* TODO: Remove the password from the session and all user harmful data
		 * Either remove it from the session on the next request
		 * Or create special class just for the user registration
		*/
		
		response.sendRedirect("registrationcomplete.jsp");
	}

}
